//
//  ModifyDeliveryInfoViewController.m
//  ELife
//
//  Created by  刘奇男 on 11-5-20.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "Constants.h"
#import "M13UserDefaults.h"
#import "GDataXMLNode.h"
#import "ELifeAppDelegate.h"
#import "GTMBase64.h"
#import "AlertView.h"
#import "GetMyData.h"
#import "ModifyDeliveryInfoViewController.h"


@implementation ModifyDeliveryInfoViewController

@synthesize address, name, phoneNumber, zipcode, infoModel;


- (void)add
{
    
//    6.1 添加邮寄地址
//    请求地址: /mailing_address.php
//    请求参数: action => addmailingaddress
//    user_id => 用户ID
//    mail_people => 联系人
//    mail_address => 邮寄地址
//    mail_zipcode => 邮编
//    mail_email => EMAIL（可空）
//    mail_phone => 联系电话
//    mail_accept => 最佳配送时间（可空）
//    返回参数: mail_id => 邮寄地址ID
//    返回格式事例: <?xml version="1.0" encoding="UTF-8"?><msg><head><returncode>0</returncode><transcode>addmailingaddress</transcode></head><body><mail_id>76</mail_id></body></msg>
    
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"mailing_address.php"]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:3];
    if (self.infoModel == nil)
    {
        [param setObject:@"addmailingaddress" forKey:@"action"];
    }else
    {
        [param setObject:@"editmailingaddress" forKey:@"action"];
        
        [param setObject:self.infoModel.mail_id forKey:@"mail_id"];
    }
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    [param setObject:[GetMyData getUserId] forKey:@"user_id"];
    
    
    [param setObject:self.address.text forKey:@"mail_address"];
    [param setObject:self.name.text forKey:@"mail_people"];
    [param setObject:self.zipcode.text forKey:@"mail_zipcode"];
    [param setObject:self.phoneNumber.text forKey:@"mail_phone"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"iRequestAddFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[[ELifeAppDelegate App] httpRequestPoint]openUrl:dic postParam:param target:self];    [[ELifeAppDelegate App] showProgressDialog:@"请稍候"];
}

- (void)iRequestAddFinished:(NSData *)response
{
    //    返回格式事例: <?xml version="1.0" encoding="UTF-8"?><msg><head><returncode>0</returncode><transcode>addmailingaddress</transcode></head><body><mail_id>76</mail_id></body></msg>

    [[ELifeAppDelegate App] hideProgressDialog];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    
    GDataXMLElement* rootElement = [doc rootElement];    
    NSLog(@"rootElement:------%@\n", rootElement);
    
    GDataXMLElement* headsElement = [[rootElement elementsForName:@"head"]objectAtIndex:0];
    
    NSString* transcode = [[[headsElement elementsForName:@"transcode"] objectAtIndex:0] stringValue];
   
    
    GDataXMLNode* returnCode = [[headsElement elementsForName:@"returncode"] objectAtIndex:0];
    NSInteger code = [[returnCode stringValue] intValue];
    if (code == -105){
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录"
                                                       delegate:self cancelButtonTitle:@"取消" otherButtonTitles: @"确定", nil];
        [alert show];
        [alert release];
        [doc release];
        return;
    } else if (code != 0){
        [AlertView showAlert:@"修改失败"];
        [doc release];
        return;
    } 
    
    [doc release];
    
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    NSLog(@"-----bodyElement-----%@\n", bodyElement);
    
    if ([transcode isEqualToString:@"editmailingaddress"])
    {
        
//        [AlertView showAlert:@"修改成功"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"修改成功"
                                                       delegate:self cancelButtonTitle:nil otherButtonTitles: @"确定", nil];
        [alert show];
        [alert release];
        return;
    }
   
    NSString* mailId = [[[bodyElement elementsForName:@"mail_id"] objectAtIndex:0]stringValue];
//    [[bodyElement elementsForName:@"mail_id"]objectAtIndex:0] stringValue];
    NSLog(@"-----mailId-----%@\n", mailId);
    [AlertView showAlert:@"添加成功"];
}

- (void) setModel:(DeliveryInfoModel*) model
{
    self.infoModel = model;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
    
    [address release];
    [name release];
    [phoneNumber release];
    [zipcode release];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [phoneNumber setDelegate:self];
    [name setDelegate:self];
    [address setDelegate:self];
    [zipcode setDelegate:self];
    
    
    [self.navigationItem setTitle:@"配送资料"]; 
    
    if (infoModel != nil)
    {
        [phoneNumber setText:infoModel.mail_phone];
        [name setText:infoModel.mail_people];
        [address setText:infoModel.mail_address];
        [zipcode setText:infoModel.mail_zipcode];
    }
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(IBAction)confirm:(id)sender
{
//    [self.navigationController popViewControllerAnimated:YES];
    [self add];
}

-(IBAction)cancel:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	// the user pressed the "Done" button, so dismiss the keyboard
	[textField resignFirstResponder];
	return YES;
}

- (IBAction)closeKeypad:(id)sender
{
    [phoneNumber resignFirstResponder];
    [name resignFirstResponder];
    [address resignFirstResponder];
    [zipcode resignFirstResponder];
    
    [sender resignFirstResponder];
}


@end
